package com.shuimutong.paxos.demo.controller;

import com.alibaba.fastjson.JSONObject;
import com.shuimutong.gmvc.annotation.XController;
import com.shuimutong.gmvc.annotation.XRequestMapping;
import com.shuimutong.gmvc.util.RequestResolveUtil;
import com.shuimutong.paxos.demo.bean.bo.ProposalBo;
import com.shuimutong.paxos.demo.bean.dto.PrepareResDto;
import com.shuimutong.paxos.demo.service.AcceptorService;
import com.shuimutong.paxos.demo.service.impl.Acceptor2ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Slf4j
@XController
@XRequestMapping("/accpetor2")
public class Acceptor2Controller extends BaseController {
    private AcceptorService acceptorService = new Acceptor2ServiceImpl();

    @XRequestMapping("/pre")
    public void prepare(HttpServletRequest request, HttpServletResponse reponse) {
        ProposalBo proposal = null;
        try {
            String body = RequestResolveUtil.readBodyStr(request);
            if(StringUtils.isNotBlank(body)) {
                proposal = JSONObject.parseObject(body, ProposalBo.class);
            }
        } catch (IOException e) {
            log.error("prepare解析参数异常", e);
        }
        if(proposal == null || proposal.getCode() <= 0) {
            RequestResolveUtil.returnJson(request, reponse, paramErr("参数解析失败，或者code非法"));
            return;
        }
        PrepareResDto res = acceptorService.prepare(proposal);
        RequestResolveUtil.returnJson(request, reponse, JSONObject.toJSONString(res));
    }

    @XRequestMapping("/acc")
    public void accept(HttpServletRequest request, HttpServletResponse reponse) {
        ProposalBo proposal = null;
        try {
            String body = RequestResolveUtil.readBodyStr(request);
            if(StringUtils.isNotBlank(body)) {
                proposal = JSONObject.parseObject(body, ProposalBo.class);
            }
        } catch (IOException e) {
            log.error("accept解析参数异常", e);
        }
        if(proposal == null || proposal.getCode() <= 0 || StringUtils.isBlank(proposal.getVal())) {
            RequestResolveUtil.returnJson(request, reponse, paramErr("参数解析失败，或者code val非法"));
            return;
        }
        int res = acceptorService.accept(proposal);
        RequestResolveUtil.returnJson(request, reponse, String.valueOf(res));
    }
}
